<template>
  <div class="map-box">
    <div class="carInfoBox" v-if="mapStatus == 1">
      <div class="carInfo">
        <span>货运单号：</span>
        <span class="carNo">{{ carInfo.label }}</span>
      </div>
      <p class="title">运输路线信息:</p>
      <div class="rote-box">
        <el-timeline :reverse="true">
          <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              icon="el-icon-coordinate"
              type="primary"
              :color="activity.color"
              size="large"
              :timestamp="activity.timestamp"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
    <div class="returnBtn" @click="addMarker" v-if="mapStatus == 1">返回</div>
    <div id="container"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import moment from "moment";
import { ElMessage } from 'element-plus'

// 定义图片路径
const truckIconUrl = new URL('../../assets/truck.jpg', import.meta.url).href;
const warehouseIconUrl = new URL('../../assets/warehouse.jpg', import.meta.url).href;

export default {
  name: "map-view",
  props: ["lntlat", "carInfo"],
  data() {
    return {
      map: null,
      marker: null,
      routeLine: null,
      startMarker: null,
      endMarker: null,
      activities: [
        { content: "加载中...", timestamp: "", color: "#409eff" },
        { content: "加载中...", timestamp: "", color: "#67c23a" },
      ],
      mapStatus: 0,
      amap: null, // 保存AMap实例
    };
  },
  watch: {
    lntlat: {
      handler: function (newVal) {
        this.$nextTick(() => {
          if (this.map && newVal && newVal.length) {
            this.removeMarker();
            this.addMarker();
          }
        });
      },
      deep: true,
    },
    carInfo: {
      handler: function(newVal) {
        if (newVal && newVal.rotes) {
          this.activities[0].timestamp = newVal.rotes.endTime || moment().format("YYYY-MM-DD HH:mm");
          this.activities[1].timestamp = newVal.rotes.startTime || moment().subtract(1, "day").format("YYYY-MM-DD HH:mm");
        }
      },
      deep: true,
      immediate: true
    },
  },
  mounted() {
    if (!window._AMapSecurityConfig) {
      console.error("请先设置高德地图安全密钥");
      ElMessage.error("地图初始化失败：未配置安全密钥");
    } else {
      this.initAMap();
    }
  },
  unmounted() {
    // 彻底销毁地图实例
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
    this.amap = null;
    this.marker = null;
    this.routeLine = null;
    this.startMarker = null;
    this.endMarker = null;
    // 清除全局变量引用
    if (window.calcDriving) {
      delete window.calcDriving;
    }
  },
  methods: {
    initAMap() {
      let that = this;
      AMapLoader.load({
        key: "4d73168b715b4d45c346b0032610bc12",
        version: "2.0",
        plugins: [
          "AMap.ToolBar", "AMap.Scale", "AMap.HawkEye",
          "AMap.MapType", "AMap.Geolocation", "AMap.ControlBar",
          "AMap.MoveAnimation", "AMap.Driving", "AMap.Geocoder",
        ],
      })
          .then((AMap) => {
            that.amap = AMap;
            window.AMap = AMap;

            that.map = new AMap.Map("container", {
              viewMode: "3D",
              zooms: [5,14],
              center: that.lntlat && that.lntlat[0] ? that.lntlat[0] : [116.397428, 39.90923],
              pitch: 45,
            });

            that.map.addControl(new AMap.ToolBar());
            that.map.addControl(new AMap.Scale());

            if (that.lntlat && that.lntlat.length) {
              that.addMarker();
            }

            // 使用箭头函数确保this指向正确
            window.calcDriving = () => that.calcDriving();
          })
          .catch((e) => {
            console.error("地图初始化失败:", e);
            ElMessage.error("地图加载失败，请刷新页面重试");
          });
    },
    removeMarker() {
      if (this.marker && this.map) {
        this.map.remove(this.marker);
        this.marker = null;
      }
    },
    removeRouteLine() {
      if (this.startMarker && this.map) this.map.remove(this.startMarker);
      if (this.endMarker && this.map) this.map.remove(this.endMarker);
      if (this.routeLine && this.map) this.map.remove(this.routeLine);
      this.startMarker = null;
      this.endMarker = null;
      this.routeLine = null;
    },
    addMarker() {
      if (!this.map || !this.lntlat || !this.lntlat.length) return;

      this.removeRouteLine();
      this.mapStatus = 0;

      const icon = new this.amap.Icon({
        size: new this.amap.Size(32, 32),
        image: truckIconUrl,
        imageSize: new this.amap.Size(32, 32),
      });

      this.marker = new this.amap.Marker({
        icon: icon,
        position: this.lntlat[0],
        offset: new this.amap.Pixel(-16, -16),
      });

      this.map.add(this.marker);
      this.map.setFitView([this.marker]);

      const infoWindowContent = `
      <div class="map-info">
        <div class="info-item"><span>货运单:</span><span>${this.carInfo.label || "--"}</span></div>
        <div class="info-item"><span>车队:</span><span>${this.carInfo.parentLabel || "--"}</span></div>
        <div class="info-item"><span>司机:</span><span>${this.carInfo.driver || "--"}</span></div>
        <div class="line"></div>
        <div class="button" onclick="calcDriving()">查看运输路线 ></div>
      </div>
      `;

      const infoWindow = new this.amap.InfoWindow({
        position: this.lntlat[0],
        offset: new this.amap.Pixel(0, -30),
        content: infoWindowContent,
      });

      infoWindow.open(this.map);
      this.marker.on("click", () => infoWindow.open(this.map));
    },
    regeoCode(lnglat, id) {
      if (!this.amap) return;

      const geocoder = new this.amap.Geocoder({ radius: 1000 });

      geocoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.activities[id].content = result.regeocode.formattedAddress;
        } else {
          this.activities[id].content = "地址解析失败";
          console.log("根据经纬度查询地址失败");
        }
      });
    },
    calcDriving() {
      if (!this.carInfo?.rotes) return;

      this.removeMarker();
      this.map.clearInfoWindow();
      this.mapStatus = 1;

      const startLocation = this.carInfo.rotes.startLocation;
      const endLocation = this.carInfo.rotes.endLocation;

      this.regeoCode(startLocation, 1);
      this.regeoCode(endLocation, 0);

      const drivingOption = {
        policy: this.amap.DrivingPolicy.LEAST_TIME,
        ferry: 1,
        province: "鲁",
      };

      const driving = new this.amap.Driving(drivingOption);

      driving.search(startLocation, endLocation, (status, result) => {
        if (status === "complete" && result.routes && result.routes.length) {
          this.drawRoute(result.routes[0]);
        } else {
          console.error("获取路线数据失败：", result);
          ElMessage.error("路线规划失败，请重试");
        }
      });
    },
    drawRoute(route) {
      const path = this.parseRouteToPath(route);

      const icon = new this.amap.Icon({
        size: new this.amap.Size(32, 32),
        image: truckIconUrl,
        imageSize: new this.amap.Size(32, 32),
      });

      this.startMarker = new this.amap.Marker({
        position: path[0],
        icon: icon,
        map: this.map,
        offset: new this.amap.Pixel(-16, -16),
        title: "起点",
      });

      const endIcon = new this.amap.Icon({
        size: new this.amap.Size(32, 32),
        image: warehouseIconUrl,
        imageSize: new this.amap.Size(32, 32),
      });

      this.endMarker = new this.amap.Marker({
        position: path[path.length - 1],
        icon: endIcon,
        map: this.map,
        offset: new this.amap.Pixel(-16, -16),
        title: "终点",
      });

      this.routeLine = new this.amap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: "#ffeeee",
        borderWeight: 2,
        strokeWeight: 5,
        strokeOpacity: 0.9,
        strokeColor: "#0091ff",
        lineJoin: "round",
      });

      this.map.add(this.routeLine);
      this.map.setFitView([this.startMarker, this.endMarker, this.routeLine]);
    },
    parseRouteToPath(route) {
      const path = [];
      for (let i = 0, l = route.steps.length; i < l; i++) {
        const step = route.steps[i];
        for (let j = 0, n = step.path.length; j < n; j++) {
          path.push(step.path[j]);
        }
      }
      return path;
    },
  },
};
</script>
<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
}
.map-box {
  position: relative;
  width: 100%;
  height: 100%;

  .returnBtn {
    position: absolute;
    z-index: 999;
    right: 20px;
    top: 20px;
    padding: 10px 30px;
    border: 1px solid #3c9efb;
    background: #1e4bc3;
    color: #f2f2f2;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background: #285fcc;
    }
  }

  .carInfoBox {
    position: absolute;
    z-index: 999;
    left: 20px;
    top: 20px;
    background: rgba(40, 57, 151, 0.9);
    color: #fff;
    padding: 20px;
    font-size: 14px;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .carInfo {
      margin-bottom: 10px;
      font-size: 14px;
    }

    .carNo {
      margin-left: 20px;
      font-weight: bold;
    }

    .title {
      margin-bottom: 10px;
      font-weight: bold;
      padding-bottom: 5px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    .rote-box {
      padding: 10px;
    }
  }
}

::v-deep {
  .el-timeline-item__node--large {
    left: -5px;
    width: 20px;
    height: 20px;
  }

  .el-timeline-item__wrapper {
    padding-bottom: 20px;
  }

  .el-timeline-item__content {
    color: #fff;
  }

  .el-timeline-item__timestamp {
    color: #bec3cd;
  }

  .el-timeline-item {
    padding-bottom: 0;
  }

  .el-timeline-item:nth-child(2) .el-timeline-item__wrapper {
    padding-bottom: 0px;
  }

  .amap-info-content {
    background: rgba(40, 57, 151, 0.9);
    border: none;
    border-radius: 4px;
  }

  .bottom-center .amap-info-sharp {
    border-color: rgba(40, 57, 151, 0.9);
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
  }

  .map-info {
    font-size: 14px;
    color: bisque;
    width: 220px;
  }

  .info-item {
    width: 100%;
    display: flex;
    span {
      display: inline-block;
      width: 50%;
      padding: 4px 0;
    }
  }

  .line {
    width: 100%;
    height: 1px;
    background: #6ca3da;
    margin: 8px 0;
  }

  .button {
    text-align: center;
    padding: 6px 0;
    cursor: pointer;
    color: #409eff;
    transition: all 0.3s;

    &:hover {
      color: #69b1ff;
    }
  }
}
</style>